package com.imagecollector.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Author: wrf
 * @Date: 2024/6/28 9:20
 * @Description: Redis 配置类
 */
/**
 * Redis配置类
 * 用于配置Redis模板及其相关序列化器
 */
@Configuration
public class RedisConfig {

    /**
     * 创建并配置RedisTemplate bean
     * RedisTemplate是Spring Data Redis提供的一个用于操作Redis的模板类
     *
     * @param redisConnectionFactory Redis连接工厂，用于创建Redis连接
     * @return 配置好的RedisTemplate实例
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // 设置连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 设置键的序列化方式为StringRedisSerializer
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 设置值的序列化方式为GenericJackson2JsonRedisSerializer，支持Java对象的序列化和反序列化
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        // 设置哈希键的序列化方式为StringRedisSerializer
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // 设置哈希值的序列化方式为GenericJackson2JsonRedisSerializer
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        // 初始化RedisTemplate配置
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

}

